<template>
  <!-- 更新月安全交底计划 -->
  <base-breadcrumb>
    <a-card :bordered="false">
      <div class="page-header table-page-search-wrapper">
        <title-name :title="pageType === 'look' ? '信息详情' : '基本信息'" />
        <a-form-model
          ref="form"
          :model="formInfo"
          :rules="rules"
          :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
        >
          <a-row :gutter="24">
            <a-col
              :md="16"
              :sm="16"
            >
              <a-form-model-item
                label="所属单位"
                prop="projectId"
              >
                <span v-if="pageType === 'look'">{{ formInfo.viewName }}</span>
                <org-tree-select
                  v-else
                  v-model="formInfo.projectId"
                  placeholder="请选择"
                  :disabled="isDisabled"
                  is-auto-select-first
                  is-need-auth
                  check-strictly
                  @select="selectOrg"
                  @change="getOrganizePeopleList"
                />
              </a-form-model-item>
            </a-col>
            <!--                        <a-col :md="8" :sm="8">-->
            <!--                            <a-form-model-item label="所属分公司" prop="branchComId">-->
            <!--                                <span v-if="pageType === 'look'">{{ formInfo.branchComName }}</span>-->
            <!--                                <SelectSubCompany-->
            <!--                                    v-else-->
            <!--                                    placeholder="请选择"-->
            <!--                                    v-model="formInfo.branchComId"-->
            <!--                                    :disabled="isDisabled"-->
            <!--                                ></SelectSubCompany>-->
            <!--                            </a-form-model-item>-->
            <!--                        </a-col>-->
            <!--                        <a-col :md="8" :sm="8">-->
            <!--                            <a-form-model-item label="所属项目" prop="projectId">-->
            <!--                                <span v-if="pageType === 'look'">{{ formInfo.projectName }}</span>-->
            <!--                                <SelectProject-->
            <!--                                    v-else-->
            <!--                                    placeholder="请选择"-->
            <!--                                    v-model="formInfo.projectId"-->
            <!--                                    :form="formInfo"-->
            <!--                                    :isClear="id == ''"-->
            <!--                                    keyValue="branchComId"-->
            <!--                                    :disabled="isDisabled"-->
            <!--                                    @change="getOrganizePeopleList()"-->
            <!--                                ></SelectProject>-->
            <!--                            </a-form-model-item>-->
            <!--                        </a-col>-->
            <a-col :span="8">
              <a-form-model-item
                label="计划月份"
                prop="planMonth"
              >
                <span v-if="pageType === 'look'">{{ formInfo.planMonth }}</span>
                <a-month-picker
                  v-else
                  v-model="formInfo.planMonth"
                  :disabled-date="disabledMonth"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="名称"
                prop="name"
              >
                <span v-if="pageType === 'look'">{{ formInfo.name }}</span>
                <BaseInput
                  v-else
                  v-model="formInfo.name"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>

    <div class="page-body">
      <a-card :bordered="false">
        <title-name title="月安全交底计划表" />
        <div
          v-if="pageType !== 'look'"
          class="table-operateors mb20"
        >
          <a-button
            type="primary"
            @click="
              openModa()
              visible = true
              isEdit = false
              modalData = {}
            "
          >
            添加计划项
          </a-button>
          <!-- 导入 -->
          <ExcelImportButton
            ref="excelImportButton"
            icon="import"
            :disabled="pageType == 'look'"
            class="ml20"
            @handleSubmit="handleSubmit"
          />
        </div>
        <s-table
          ref="table"
          :bordered="true"
          size="default"
          row-key="key"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="false"
        >
          <template
            slot="index"
            slot-scope="text, record, index"
          >
            {{ index + 1 }}
          </template>
          <template
            v-if="pageType !== 'look'"
            slot="operator"
            slot-scope="text, record"
          >
            <a
              class="base-btn"
              @click="
                openModa(record)
                visible = true
                isEdit = true
                modalData = record
              "
            >编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除?"
              @confirm="() => delItem(record)"
            >
              <a>删除</a>
            </a-popconfirm>
            <!-- <a class="base-btn" @click="delItem(record)">删除</a> -->
          </template>
        </s-table>
      </a-card>
      <div
        v-if="pageType !== 'look'"
        class="tool-btns page-btn-right-top"
      >
        <a-button
          v-if="id != '' && formInfo.auditStatus == 'DRAFT'"
          type="danger"
          :loading="loading.DELETE"
          @click="handleSave('DELETE')"
        >
          删除草稿
        </a-button>
        <a-button
          type="primary"
          :disabled="isSave"
          :loading="loading.DRAFT"
          @click="handleSave('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          type="primary"
          :disabled="isSave"
          :loading="loading.SUBMITTED"
          @click="handleSave('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
      <div
        v-else
        class="tool-btns page-btn-right-top"
      >
        <a-button
          type="primary"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </div>

    <a-modal
      :title="pageType === 'edit' ? '月安全交底计划项编辑' : '月安全交底计划项添加'"
      cancel-text="取消"
      ok-text="保存"
      :width="900"
      :visible="visible"
      @cancel="
        cancel()
        visible = false
      "
      @ok="submitModal()"
    >
      <a-form-model
        ref="ruleFormModal"
        :model="modalData"
        :rules="rulesModal"
        :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="交底编号"
              prop="number"
            >
              <BaseInput
                v-model="modalData.number"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="安全技术交底名称"
              prop="name"
            >
              <BaseInput
                v-model="modalData.name"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="交底人"
              prop="employeeId"
            >
              <a-select
                v-model="modalData.employeeId"
                show-search
                placeholder="请选择"
              >
                <a-select-option
                  v-for="i in organizePeopleList"
                  :key="i.employeeId"
                  :value="i.employeeId"
                >
                  {{ i.employeeName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="交底日期"
              prop="confessDate"
            >
              <a-date-picker
                v-model="modalData.confessDate"
                :disabled-date="disabledMonth"
                :default-picker-value="this.moment().startOf('month').subtract('month', -1)"
                placeholder="请选择"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item label="备注">
              <BaseTextarea
                v-model="modalData.remark"
                style="resize: none"
                placeholder="请输入"
                :rows="2"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import { getSubcontractor } from '@/api/businessAffairs/sml'
import { getSelectListByType } from '@/api/safetySupervision/common'
import moment from 'moment'
import ExcelImportButton from '@/components/ExcelImportButton' // excel导入按钮
import {
    getSafteyClosurePlanDetail,
    addSafteyClosurePlan,
    updateSafteyClosurePlan,
    deleteSafteyClosurePlan,
    getSafteyClosurePlanList,
} from '@/api/safetySupervision/safteyClosure'

const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        scopedSlots: { customRender: 'index' },
    },
    {
        title: '交底编号',
        dataIndex: 'number',
    },
    {
        title: '安全技术交底名称',
        dataIndex: 'name',
    },
    {
        title: '交底人',
        dataIndex: 'employeeName',
    },
    {
        title: '交底日期',
        dataIndex: 'confessDate',
    },
    {
        title: '备注',
        dataIndex: 'remark',
    },
    {
        title: ' 操作',
        dataIndex: 'operator',
        scopedSlots: { customRender: 'operator' },
    },
]
export default {
    name:'a'+Date.now(),    components: {
        SelectSubCompany,
        SelectProject,
        STable,
        ExcelImportButton,
    },
    data() {
        this.columns = columns
        return {
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
            },
            id: '',
            key: 0,
            modalData: {},
            formInfo: {
              viewName: ""
            },
            visible: false,
            isEdit: false,
            rulesModal: {
                number: [{ required: true, message: '请输入交底编号' }],
                name: [{ required: true, message: '请输入交底名称' }],
                employeeId: [{ required: true, message: '请选择交底人' }],
                confessDate: [{ required: true, message: '请选择交底日期' }],
            },
            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
                name: [{ required: true, message: '请输入名称' }],
                planMonth: [{ required: true, message: '请选择月份', trigger: 'blur' }],
            },

            cacheitemServiceVO: [],
            formInfo: {
                itemServiceVO: [],
                planMonth: moment().add(0, 'months'),
            },
            organizePeopleList: [], //项目人员列表
            subcontractorList: [], //分包商列表
            selectList: [], //验收分类列表
            isSave: false,
            loadData: (parameter) => {
                if (this.formInfo.itemServiceVO.length > 0) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.formInfo.itemServiceVO,
                        })
                    })
                }
            },
            importCheck: {
                交底编号: 'number',
                安全技术交底名称: 'name',
                交底人: 'employeeName',
                交底日期: 'confessDate',
                '备  注': 'remark',
            },
            //             importCheck: {
            //     员工编号: 'number',
            //     员工姓名: 'name',
            //     签名章: 'employeeName',
            //     组织: 'confessDate',
            //     部门: 'remark',
            //      岗位: 'remark',
            //       证件号码: 'remark',
            //      出生日期: 'remark',
            //       年龄: 'remark',
            //      员工状态: 'remark',
            // },
        }
    },
    computed: {
        pageType() {
            return this.$route.query.pageType || 'look'
        },
        isDisabled() {
            return this.pageType == 'edit'
        },
    },
    created() {
        this.id = this.$route.query.id
        this.$route.meta.title = this.id == '' ? '月安全交底计划新增' : '月安全交底计划编辑'
        let tagat = true
        this.columns.forEach((i) => {
            if (i.dataIndex == 'operator') {
                tagat = false
            }
        })
        if (this.$route.query.pageType == 'look') {
            this.$route.meta.title = '月安全交底计划查看'
            if (!tagat) {
                this.columns.length = this.columns.length - 1
            }
            console.log(this.columns)
        } else {
            if (tagat) {
                this.columns.push({ title: ' 操作', dataIndex: 'operator', scopedSlots: { customRender: 'operator' } })
            }
        }
    },
    mounted() {
        this.getDetail()
    },
    methods: {
        /**
         * 导入记录
         */
        handleSubmit(e) {
            let form = []
            console.log(e)
            for (let index in e) {
                form.push({})
                let keys = e[index]
                let listItem = form[index]
                // 校验excel的表头数量
                // if (Object.keys(keys)?.length === 5) {
                // 校验excel的表头字段
                for (let i in this.importCheck) {
                    let item = this.importCheck[i]
                    if (!Object.keys(keys).includes(i) && i != '备  注') {
                        this.$message.warning(`${i}缺失`)
                        return
                    } else {
                        listItem[item] = keys[i]
                        if (item === 'confessDate') {
                              if(!/^\d{4}-\d{2}-\d{2}$/.test(listItem[item])){
                                this.$message.warning(`${i}日期格式错误!例如2020-01-01`)
                                return
                              }
                            }
                    }
                }
                // } else {
                //     this.$message.warning('数据不完整')
                //     return
                // }
            }
            this.formInfo.itemServiceVO = this.formInfo.itemServiceVO.concat(form)
            this.$refs.table.refresh(true)
        },
        async isAddPlan() {
            console.log(this.formInfo.planMonth)
            if (!this.formInfo.planMonth) return
            const [err, res] = await getSafteyClosurePlanList({
                projectId: this.formInfo.projectId,
                isPermissions: '0',
            })
            let plan = res.data.filter(
                (i) =>
                    i.projectId == this.formInfo.projectId && i.planMonth == this.formInfo.planMonth
            )
            if (plan.length > 0) {
                this.$message.warning('该项目在该月份已有交底计划！')
                this.isSave = true
            } else {
                this.isSave = false
            }
        },
        disabledMonth(current) {
            return (
                (current && current < this.moment().startOf('month')) ||
                current > this.moment().endOf('month').subtract('month', -1).endOf('month')
            )
        },
      selectOrg(val) {
          this.formInfo.branchComId = val[val.length - 2].orgId
          this.getOrganizePeopleList()
      },
        //获取项目下的人员列表
        getOrganizePeopleList() {
            if (!this.formInfo.projectId) return
            let params = {
                id: this.formInfo.projectId,
            }
            getOrganizePeopleList(params).then((res) => {
                let obj = {}
                res.data = res.data.reduce((cur, next) => {
                    obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
                    return cur
                }, []) //设置cur默认类型为数组，并且初始值为空的数组
                console.log(res.data)
                this.organizePeopleList = res.data || []
            })
            if(this.pageType =='add'){
                     this.isAddPlan()
            }

            console.log(this.organizePeopleList)
        },

        delItem(data) {
            this.formInfo.itemServiceVO.forEach((item, idx) => {
                if (item.key == data.key) {
                    this.formInfo.itemServiceVO.splice(idx, 1)
                }
            })
        },
        submitModal() {
            let that = this
            if (!this.validateModalForm()) return

            console.log(this.modalData)
            if (typeof this.modalData.confessDate != 'string') {
                this.modalData.confessDate = this.modalData.confessDate.format('YYYY-MM-DD')
            }

            console.log(this.modalData)

            //交底人name
            this.modalData.employeeName = this.organizePeopleList.filter(
                (item) => this.modalData.employeeId == item.employeeId
            )[0].employeeName

            if (this.isEdit) {
                Object.assign(
                    this.modalData,
                    this.formInfo.itemServiceVO.filter((item) => this.modalData.key === item.key)[0]
                )
                console.log(this.formInfo)
            } else {
                this.modalData.key = this.key
                this.key++
                this.formInfo.itemServiceVO.push(this.modalData)
            }
            this.visible = false
            this.$refs.table.refresh(true)
        },
        async getDetail() {
            const { id } = this.$route.query
            if (!id) return
            const params = {
                id,
            }
            this.$refs.table.localLoading = true
            const [err, res] = await getSafteyClosurePlanDetail(params)
            this.$refs.table.localLoading = false
            if (!err) {
                this.formInfo = {
                    ...this.formInfo,
                    ...res.data,
                    viewName: ""
                }
              this.formInfo.viewName = this.formInfo.branchComName + '/' +this.formInfo.projectName
            }

            this.getOrganizePeopleList()
            if (this.formInfo.itemServiceVO == null) {
                this.formInfo.itemServiceVO = []
            } else {
                this.formInfo.itemServiceVO.forEach((item, i) => {
                    item.key = this.key
                    this.key++
                })
            }

            this.$refs.table.refresh(true)
        },
        openModa(record) {
            this.cacheitemServiceVO = []
            this.cacheitemServiceVO = this.formInfo.itemServiceVO.map((item) => ({ ...item }))
        },
        cancel() {
            const newData = this.formInfo.itemServiceVO
            const target = newData.filter((item) => this.modalData.key === item.key)[0]

            if (target) {
                Object.assign(target, this.cacheitemServiceVO.filter((item) => this.modalData.key === item.key)[0])

                this.formInfo.itemServiceVO = newData
            }
        },
        validateForm() {
            let flag = false
            this.$refs.form.validate((valid) => {
                flag = valid
            })
            return flag
        },
        validateModalForm() {
            let flag = false
            this.$refs.ruleFormModal.validate((valid) => {
                flag = valid
            })
            return flag
        },
        async deleteSafteyClosurePlan(params) {
            const [err, res] = await deleteSafteyClosurePlan(params)
            if (!err) {
                this.$message.success('删除成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        async handleSave(status) {
            if (status !== 'DELETE' && !this.validateForm()) return
            if (this.loading[status]) return
            this.loading[status] = true
            this.formInfo.itemDTO = this.formInfo.itemServiceVO
            this.formInfo.itemDTO.forEach((item) => {
                item.employeeBatchName = item.employeeName
            })
            const params = {
                ...this.formInfo,
                auditStatus: status,
                id: this.$route.query.id || void 0,
            }
            const { pageType } = this.$route.query
            const fn = pageType === 'edit' ? updateSafteyClosurePlan : addSafteyClosurePlan
            const map = {
                DELETE: deleteSafteyClosurePlan,
                DRAFT: fn,
                SUBMITTED: fn,
            }
            if (status == 'DELETE') {
                let that = this
                this.$confirm({
                    title: '温馨提示',
                    content: '确定是否删除数据？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                        return that.deleteSafteyClosurePlan(params)
                    },
                })
            } else {
                const [err, res] = await map[status](params)
                if (!err) {
                    this.$message.success('成功')
                    this.handleClose()
                }
            }

            this.loading[status] = false
        },
        handleClose() {
            this.$multiTab.close(this.$route.fullpath)
            //  history.go(-1)
        },
    },
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.page-header {
    .header-row {
        display: flex;
        .flex-content {
            flex: auto;
        }
        .divider {
            margin: 0 12px;
        }
        .expand-btn {
            margin-left: 8px;
            font-size: 14px;
        }
    }
}
.page-body {
    .table-operateors {
        .ant-btn + .ant-btn {
            margin-left: 12px;
        }
    }
}
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
</style>
